/*
 * @Author: hx 2542123711@QQ.com
 * @Date: 2025-01-13 19:47:36
 * @LastEditors: hx 2542123711@QQ.com
 * @LastEditTime: 2025-01-13 20:44:00
 * @FilePath: /class_socket/tcp_socket/TcpClient.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include "Log.hpp"

#define INBUFFER_SIZE 4096

using namespace std;

Log log;

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cout << "Please Enter Again" << endl;
        return 1;
    }

    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    struct sockaddr_in server;
    socklen_t len = sizeof(server);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    // 操作系统自动帮我们bind
    // 如果没有连接上服务器, clinet需要实现重连功能
    while (true)
    {
        int sockfd = 0;
        int cnt = 5;
        bool reinteract = false;
        do
        {
            sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (sockfd < 0)
            {
                cerr << "socket create error" << endl;
                return 2;
            }

            if (connect(sockfd, (struct sockaddr *)&server, len) < 0)
            {
                //重连记时
                cerr << "drying reinteract..., " << cnt << endl;
                cnt--;
                sleep(2);
                reinteract = true;
            }
            else
            {
                //重连成功
                break;
            }
        } while (cnt && reinteract);

        if (cnt == 0)
        {
            log(Fatal, "offoline...");
            return 3;
        }

        string message;

        cout << "Please Enter@ " << endl;
        getline(cin, message);

        ssize_t m = write(sockfd, message.c_str(), message.size());
        if (m < 0)
        {
            log(Warning, "error:%d, errorstring:%s", errno, strerror(errno));
        }

        char inbuffer[INBUFFER_SIZE];
        ssize_t n = read(sockfd, inbuffer, sizeof(inbuffer));
        if (n > 0)
        {
            inbuffer[n] = 0;
            cout << inbuffer << endl;
        }

        close(sockfd);
    }

    return 0;
}